package com.supercell.controller;

import com.supercell.misc.data.TCPConnectionStatus;
import com.supercell.misc.json.JSONUtil;
import com.supercell.service.TCPConnectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by WUJO2 on 7/15/2016.
 */
@Controller
@RequestMapping(path = "httpServer")
public class HTTPConnectionController {
    @Autowired
    private TCPConnectionService tcpConnectionService;

    @RequestMapping(path = "startCRMServer", method = {RequestMethod.GET, RequestMethod.POST})
    public void startCRMServer() {
        try {
            tcpConnectionService.startTCPServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(path = "stopCRMServer", method = {RequestMethod.GET, RequestMethod.POST})
    public void stopCRMServer() {
        try {
            tcpConnectionService.stopTCPServer();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(path = "serverStatus", method = RequestMethod.GET)
    public void getServerStatus(HttpServletResponse response) {
        List<TCPConnectionStatus> tcpConnectionStatusList = tcpConnectionService.getTCPConnectionStatus();
        String jsonString = JSONUtil.convertToJSON(tcpConnectionStatusList);
        JSONUtil.writeJSON(response, jsonString);
    }

    @RequestMapping(path = "isTCPServerRunning", method = RequestMethod.GET)
    public void isTCPServerRunning(HttpServletResponse response) {
        Boolean isRunning = tcpConnectionService.isTCPServerRunning();
        String jsonString = JSONUtil.convertToJSON(isRunning);
        JSONUtil.writeJSON(response, jsonString);
    }
}
